/**
 * date常用工具类
 */
export default {
	/**
	 * 时间戳转为多久之前
	 * @param String timestamp 时间戳
	 * @param String | Boolean format 如果为时间格式字符串，超出一定时间范围，返回固定的时间格式；
	 * 如果为布尔值false，无论什么时间，都返回多久以前的格式
	 */
	timeFrom(timestamp = null, format = 'yyyy-MM-dd') {
		if (timestamp == null) timestamp = Number(new Date())
		timestamp = parseInt(timestamp)
		// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
		if (timestamp.toString().length == 10) timestamp *= 1000
		let timer = (new Date()).getTime() - timestamp
		timer = parseInt(timer / 1000)
		// 如果小于5分钟,则返回"刚刚",其他以此类推
		let tips = ''
		switch (true) {
			case timer < 300:
				tips = '刚刚'
				break
			case timer >= 300 && timer < 3600:
				tips = `${parseInt(timer / 60)}分钟前`
				break
			case timer >= 3600 && timer < 86400:
				tips = `${parseInt(timer / 3600)}小时前`
				break
			case timer >= 86400 && timer < 2592000:
				tips = `${parseInt(timer / 86400)}天前`
				break
			default:
				// 如果format为false，则无论什么时间戳，都显示xx之前
				if (format === false) {
					if (timer >= 2592000 && timer < 365 * 86400) {
						tips = `${parseInt(timer / (86400 * 30))}个月前`
					} else {
						tips = `${parseInt(timer / (86400 * 365))}年前`
					}
				} else {
					tips = this.formatDate(timestamp, format)
				}
		}
		return tips
	},
	/**
	 * 时间/日期格式化工具
	 * @param {Long||String} date 转换的时间戳或者字符串
	 * @param {String} fmt 转换格式 如:yyyy-MM-dd hh:mm
	 * @return {String} 返回格式化后的时间
	 * @author Jie.
	 * */
	formatDate(date, fmt) {
		if (!date) return ''
		if (typeof date == "number")
			date = new Date(date)
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
		}
		let o = {
			'M+': date.getMonth() + 1,
			'd+': date.getDate(),
			'h+': date.getHours(),
			'm+': date.getMinutes(),
			's+': date.getSeconds()
		}
		for (let k in o) {
			if (new RegExp(`(${k})`).test(fmt)) {
				let str = o[k] + ''
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
			}
		}
		return fmt
	},
	/**
	 * 文本转Date
	 * @param {Object} str
	 * @param {Object} format
	 * @author Jie.
	 */
	stringToDate(str, format) {
		if (str instanceof Date) return str
		var pattern = format.replace(/(yyyy)/g, "([0-9]{4})").replace(/(yy)|(MM)|(dd)|(hh)|(mm)|(ss)/g, "([0-9]{2})")
			.replace(
				/[Mdhms]/g, "([0-9]{1,2})")
			.replace(/(fff)/g, "([0-9]{1,3})")
		var getIndex = function(expr1, expr2) {
			var index = format.indexOf(expr1)
			if (index == -1)
				index = format.indexOf(expr2)
			return index
		}
		var today = new Date()
		var returnDate
		if (new RegExp(pattern).test(str)) {
			var yPos = getIndex("yyyy", "yy")
			var mPos = getIndex("MM", "M")
			var dPos = getIndex("dd", "d")
			var hPos = getIndex("hh", "h")
			var miPos = getIndex("mm", "m")
			var sPos = getIndex("ss", "s")
			var fPos = getIndex("fff")
			var data = {
				y: 0,
				m: 0,
				d: 0,
				h: 0,
				mi: 0,
				s: 0,
				f: 0
			}
			var pos = new Array(yPos + ",y", mPos + ",m", dPos + ",d", hPos + ",h", miPos + ",mi", sPos + ",s", fPos +
				",f").sort(
				function(a, b) {
					a = parseInt(a.split(",")[0], 10)
					b = parseInt(b.split(",")[0], 10)
					return a == b ? 0 : (a > b ? 1 : -1)
				})
			var tmpIndex = 0
			var newPos = []
			for (var i = 0; i < pos.length; i++) {
				if (parseInt(pos[i].split(",")[0], 10) != -1) {
					newPos[tmpIndex] = pos[i]
					tmpIndex++
				}
			}
			var m = str.match(pattern)
			for (i = 1; i < m.length; i++) {
				if (i === 0)
					return
				var flag = newPos[i - 1].split(',')[1]
				data[flag] = m[i]
			}

			data.y = data.y || today.getFullYear()
			data.d = data.d || today.getDate()
			if (data.f !== 0)
				data.f = _full(data.f, "0", 3, false)

			if (data.y.toString().length == 2)
				data.y = parseInt("20" + data.y, 10)
			data.m -= 1
			returnDate = new Date(data.y, data.m, data.d, data.h, data.mi, data.s, data.f)
		}
		return returnDate;
	},
	/**
	 * 获取时间数组
	 * @param {Long||String} date 要获取时间数组的原时间
	 * @param {String} type 最终转换类型 
	 * @return {Array}
	 * @author Jie.
	 * */
	getDateArray(date, type) {
		if (typeof date == 'number')
			date = new Date(date)
		let aToday = date
		let tYear = aToday.getFullYear().toString()
		let tMonth = formatNum(aToday.getMonth() + 1).toString()
		let tDay = formatNum(aToday.getDate()).toString()
		let tHours = formatNum(aToday.getHours()).toString()
		let tMinutes = formatNum(aToday.getMinutes()).toString()
		let tSeconds = formatNum(aToday.getSeconds()).toString()
		if (type == 'datetime')
			return [tYear, tMonth, tDay, tHours, tMinutes, tSeconds]
		else if (type = 'date')
			return [tYear, tMonth, tDay]
	},
	/**
	 * 时间差计算
	 * @param {Object} start
	 * @param {Object} end
	 * @param {Object} interval
	 */
	dateDiff(start, end, interval) {
		start = (typeof start == 'string' || typeof start == 'number') ? new Date(start) : start
		end = (typeof end == 'string' || typeof end == 'number') ? new Date(end) : end
		interval = (typeof interval == 'undefined') ? 'd' : interval
		switch (interval) {
			case 's':
				return parseInt((end - start) / this._msForSecond, 10)
			case 'n':
				return parseInt((end - start) / this._msForMinute, 10)
			case 'h':
				return parseInt((end - start) / this._msForHour, 10)
			case 'd':
				return parseInt((end - start) / this._msForDay, 10)
			case 'w':
				return parseInt((end - start) / this._msForWeek, 10)
			case 'm':
				return (end.getMonth() + 1) + ((end.getFullYear() - start.getFullYear()) * 12) - (start.getMonth() + 1)
			case 'y':
				return end.getFullYear() - start.getFullYear()
		}
	},
	/**
	 * 时间计算
	 * @param {Object} datetime
	 * @param {Object} num
	 * @param {Object} interval
	 */
	dateIncrease(datetime, num, interval) {
		datetime = (typeof datetime == 'string' || typeof datetime == 'number') ? new Date(datetime) : datetime
		interval = (typeof interval == 'undefined' ) ? 'd' : interval
		switch (interval) {
			case 's':
				return new Date(Date.parse(datetime) + (this._msForSecond * num))
			case 'n':
				return new Date(Date.parse(datetime) + (this._msForMinute * num))
			case 'h':
				return new Date(Date.parse(datetime) + (this._msForHour * num))
			case 'd':
				return new Date(Date.parse(datetime) + (this._msForDay * num))
			case 'w':
				return new Date(Date.parse(datetime) + (this._msForWeek * num))
			case 'm':
				return new Date(datetime.getFullYear(), (datetime.getMonth()) + num, datetime.getDate(), datetime
					.getHours(),
					datetime.getMinutes(),
					datetime.getSeconds())
			case 'q':
				return new Date(datetime.getFullYear(), (datetime.getMonth()) + num * 3, datetime.getDate(), datetime
					.getHours(),
					datetime.getMinutes(),
					datetime.getSeconds())
			case 'y':
				return new Date((datetime.getFullYear() + num), datetime.getMonth(), datetime.getDate(), datetime
					.getHours(),
					datetime.getMinutes(),
					datetime.getSeconds())
		}
	},
	_msForSecond: 1000,
	_msForMinute: 60000,
	_msForHour: 3600000,
	_msForDay: 86400000, // 24*60*60*1000
	_msForWeek: 86400000 * 7
}
var formatNum = function(num) {
	return num < 10 ? '0' + num : num + ''
}
var padLeftZero = function(str) {
	return ('00' + str).substr(str.length)
}
var _full = function(str, ch, count, isLeft) {
	while (str.length < count)
		if (isLeft) str = ch + str
	else str = str + ch
	return str
}
